<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Notice;
use app\common\model\User;
use think\facade\Db;
use think\Exception;
use addons\epay\library\Service;
use addons\epay\library\Yansongda\Pay\Pay;

/**
 * 提现申请
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{
    protected $relationSearch = true;

    protected $searchFields = 'id,user.username,order_sn';
    
    /**
     * Withdraw模型对象
     * @var \app\common\model\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Withdraw;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isDepositList", $this->model->getIsDepositList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->withJoin('user')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->withJoin('user')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible([
                    'id','user_id','money','type','account','name','memo','order_sn','status','tranfer_time','create_time','update_time','is_deposit',
                    'user'=>['username']
                ]);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row)
            $this->error('未找到体现信息');

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    if ($row->status == 'apply') {
                        if ($params['status'] == 'rejected') {
                            // 提现拒绝通知
                            Notice::create([
                                'title'=>'提现申请被拒绝',
                                'content'=>'您的提现申请被拒绝。'.$params['msg'],
                                'type'=>2,
                                'user_id'=>$params['user_id'],
                                'order_id'=>0
                            ]);
                            User::money($params['money'], $params['user_id'], '拒绝提现,返还余额', 1, '余额');
                        }
                        if ($params['status'] == 'successed') {

                            // 提现同意通知
                            Notice::create([
                                'title'=>'提现申请通过',
                                'content'=>'您的提现申请已通过。',
                                'type'=>2,
                                'user_id'=>$params['user_id'],
                                'order_id'=>0
                            ]);
                            if (empty($params['transfertime'])) {
                                $params['transfertime'] = time();
                            }

                            /*if($row['type']=='wechat'){
                                $user=User::get($row['user_id']);

                                $order = [
                                    'partner_trade_no' => $row['id'],       //商户订单号
                                    'openid'           => $user['openid'],             //收款人的openid
                                    'check_name'       => 'NO_CHECK',          //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
                                    'amount'           => $params['money'] * 100,   //企业付款金额，单位为分
                                    'desc'             => "壹心仪陪诊-提现{$params['money']}元",               //付款说明
                                    'type'             => 'miniapp'
                                ];
                                $config = Service::getConfig('wechat');
                                $pay = Pay::wechat($config);
                                $transfer = $pay->transfer($order);
                                $transfer = json_encode($transfer, true);
                                adlog('提现', $transfer);
                                if (!$transfer ||!isset($transfer['return_code']) || !$transfer['return_code'] == 'SUCCESS')
                                    throw new Exception('提现失败');

                            }*/
                        }
                    }
                    $result = $row->save($params);
                    Db::commit();
                }  catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error('没有新的数据需要更新');
                }
            }
            $this->error('未获得提交信息');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
